# -*- coding:utf-8 -*-
import MySQLdb
import os
os.sys.path.append('../../utils/constants/')
from constants import *
#import constants

class userDao(object):
    "user operation about storage"
    def __init__(self, dbHandler):
        self.__copy_list = [\
                (type(''), "user_name"), \
                (type(''), "user_pass"), \
                (type(10), "birth_year"), \
                (type(10), "sex"), \
                (type(10), "creat_time"),]
        self.__db_user_table = 'users'
        self.__user_output_list = ['user_id', 'user_name', 'birth_year', 'sex', 'activity', \
                        'popularity', 'creat_time',]
        self.__db_conn = dbHandler

    def __normalize_user_name(self, user_name):
        filter_list = [' ', '\t', '\n', '\r', \
                '!','@','#','$','%','^','&','*','*','(',')','-','+','_','=',\
                ',','.','<','>','"',':','\'',';','/',]
        for x in filter_list:
            user_name = user_name.replace(x, '');
        return user_name
    def __is_valid(self, user_item):
        ret = {}
        ret['retcode'] = 0
        ret['message'] = "OK"
        if not user_item:
            ret['retcode'] = E_VALUE_NONE
            ret['message'] = 'user_item is None'
            return ret
        for key_item in self.__copy_list:
            if not user_item.has_key(key_item[1]):
                ret['retcode'] = E_KEY_NOT_EXIST
                ret['message'] = 'field[%s] not exist' % (key_item[1], )
                return ret
            if type(user_item[key_item[1]]) != key_item[0]:
                ret['retcode'] = E_VALUE_TYPE_ERROR
                ret['message'] = 'field[%s] type error. wish[%s]' % (key_item[1], key_item[0],)
                return ret
            if None == user_item[key_item[1]]:
                ret['retcode'] = E_VALUE_IS_EMPTY
                ret['message'] = 'field[%s] empty value' % (key_item[1], )
                return ret
        return ret

    def add(self, user_item):
        ret = {}
        ret['retcode'] = 0
        ret['message'] = "OK"
        check_ret = self.__is_valid(user_item)
        if 0 != check_ret['retcode']:
            return check_ret
        user_item['user_name'] = self.__normalize_user_name(user_item['user_name'])
        tmp_user = self.get_userinfo_by_name(user_item['user_name'])
        if tmp_user:
            ret['retcode'] = E_REGISTER_ALREADY_EXIST
            ret['message'] = 'user_name[%s] exists.' % (user_item['user_name'], )
            return ret
        if len(user_item['user_name']) == 0:
            ret['retcode'] = E_REGISTER_UNAME_LENGTH_ZERO
            ret['message'] = 'user_name length is zeor.'
            return ret
        elif len(user_item['user_name']) >= 22:
            # 最多七个汉字，或21个字母
            ret['retcode'] = E_REGISTER_UNAME_LENGTH_TOO_LONG
            ret['message'] = 'user_name length[%u] >max_length[32].' % (len(user_item['user_name']), )
            return ret
        user4insert = {}
        for key in self.__copy_list:
            user4insert[key[1]] = user_item[key[1]]
        field_list = 'user_name, user_pass, sex, birth_year, creat_time'
        conn = self.__db_conn._db
        value = '"%s", "%s", %u, %u, %u' % (\
                conn.escape_string(user4insert['user_name']),\
                conn.escape_string(user4insert['user_pass']),\
                user4insert['sex'],\
                user4insert['birth_year'],\
                user4insert['creat_time'],)
        strSQL = 'INSERT INTO %s (%s) VALUES (%s);' % (self.__db_user_table, field_list, value,)
        # -1- 插入user表
        #print strSQL
        try:
            self.__db_conn.execute(strSQL)
        except Exception, e:
            ret['retcode'] = E_MYSQL_FAIL
            ret['db_errno'] = e[0]
            ret['message'] = e[1]
            #print e
            return ret
        del user_item['user_pass']
        ret['retbody'] = user_item
        return ret

    def freeze(self, user_id):
        ret = {}
        ret['retcode'] = 0
        ret['message'] = "OK"
        strSQL = 'UPDATE users SET status = 1 WHERE user_id=%u;' % (user_id, )
        self.__db_conn.execute(strSQL)
        return ret

    def thaw(self, user_id):
        ret = {}
        ret['retcode'] = 0
        ret['message'] = "OK"
        strSQL = 'UPDATE %s SET status = 0 WHERE user_id=%u;' % (self.__db_user_table, user_id, )
        self.__db_conn.execute(strSQL)
        return ret

    def get_userinfo_by_id(self, user_id):
        select_list = ['user_id', 'user_name', 'status', 'sex', 'birth_year', 'creat_time', 'activity', 'popularity',]
        select_key_string = ', '.join(select_list)
        strSQL = 'SELECT %s FROM %s WHERE user_id = %u;' %\
                (select_key_string, self.__db_user_table, user_id,)
        dbret = self.__db_conn.get(strSQL)
        if dbret:
            return dbret
        else:
            return {}

    def get_userinfo_by_name(self, user_name):
        select_list = ['user_id', 'user_name', 'status', 'sex', 'birth_year', 'creat_time', 'activity', 'popularity',]
        select_key_string = ', '.join(select_list)
        user_name = self.__normalize_user_name(user_name)
        strSQL = 'SELECT %s FROM %s WHERE user_name = "%s";' %\
                (select_key_string, self.__db_user_table, self.__db_conn._db.escape_string(user_name), )
        dbret = self.__db_conn.get(strSQL)
        if dbret:
            return dbret
        else:
            return {}

    def checkin(self, user_name, user_pass):
        ret = {}
        ret['retcode'] = 0
        ret['message'] = 'OK'
        select_list = ['user_id', 'user_name', 'user_pass', 'status', 'sex',\
                'birth_year', 'creat_time', 'activity', 'popularity',]
        select_key_string = ', '.join(select_list)
        conn = self.__db_conn._db
        conn.set_character_set('utf8')
        user_name = self.__normalize_user_name(user_name)
        #user_name = 'xxoo'
        strSQL = 'SELECT %s FROM %s WHERE user_name = "%s";' %\
                (select_key_string, self.__db_user_table, conn.escape_string(user_name), )
        #print strSQL
        user_info = self.__db_conn.get(strSQL)
        if user_info:
            if user_info['user_pass'] != user_pass:
                ret['retcode'] = E_CHECKIN_PASSWORD_FAIL
                ret['message'] = 'user[%s] password error.' % (user_name, )
            elif 0 != user_info['status']:
                ret['retcode'] = E_CHECKIN_USER_FORBIDEN
                ret['message'] = 'user[%s] is forbiden.' % (user_name, )
            else:
                del user_info['user_pass']
                user_info['user_id'] = int(user_info['user_id'])
                ret['retbody'] = user_info
        else:
            ret['retcode'] = E_CHECKIN_USER_NOT_EXIST
            ret['message'] = 'user[%s] not exist.' % (user_name, )
        return ret

    def add_activity(self, user_id, inc):
        ret = {}
        ret['retcode'] = 0
        ret['message'] = "OK"
        #strSQL  = 'SET AUTOCOMMIT=0;'
        #strSQL += ' SELECT activity FROM %s WHERE user_id=%u FOR UPDATE;' % (self.__db_user_table, user_id,)
        #strSQL += ' UPDATE %s SET activity = activity+%u WHERE user_id=%u;' % (self.__db_user_table, inc, user_id)
        #strSQL += ' COMMIT; SET AUTOCOMMIT=1;'
        strSQL = 'UPDATE %s SET activity = activity+%u WHERE user_id=%u;' % (self.__db_user_table, inc, user_id)
        self.__db_conn.execute(strSQL)
        return ret

    def add_popularity(self, user_id, inc):
        ret = {}
        ret['retcode'] = 0
        ret['message'] = "OK"
        #strSQL  = 'SET AUTOCOMMIT=0;'
        #strSQL += ' SELECT popularity FROM %s WHERE user_id=%u FOR UPDATE;' % (self.__db_user_table, user_id,)
        #strSQL += ' UPDATE %s SET popularity = popularity+%u WHERE user_id=%u;' % (self.__db_user_table, inc, user_id)
        #strSQL += ' COMMIT; SET AUTOCOMMIT=1;'
        strSQL = 'UPDATE %s SET popularity = popularity+%u WHERE user_id=%u;' % (self.__db_user_table, inc, user_id)
        self.__db_conn.execute(strSQL)
        return ret
